package com.hmall.order.web;

import com.fasterxml.jackson.databind.ser.Serializers;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.config.BaseContext;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.Orderxia;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderLogisticsService;
import com.hmall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("order")
public class OrderController {

   @Autowired
   private IOrderService orderService;

   @Autowired
   private ItemClient itemClient;

   @Autowired
   private UserClient userClient;

   @Autowired
   private IOrderDetailService orderDetailService;

   @Autowired
   private IOrderLogisticsService orderLogisticsService;


   @GetMapping("{id}")
   public Order queryOrderById(@PathVariable("id") Long orderId) {
      return orderService.getById(orderId);
   }

   @PostMapping
   public Long byId(@RequestBody Orderxia orderxia){
//      log.info("ID是啥：{}",orderxia);
      Order order =new Order();
      log.info("ID是啥：{}",order.getId());
      Long itemId = orderxia.getItemId();
      //根据商品ID查询对应商品
      Item item = itemClient.selectById(itemId);

      //计算总价格
      Integer num = orderxia.getNum();


      item.setStock(item.getStock()-num);


      order.setTotalFee(num*item.getPrice());
      order.setPaymentType(orderxia.getPaymentType());
      order.setUserId(BaseContext.getCurrentId());
      order.setStatus(1);
      log.info("对象:{}",order);
      //添加
      orderService.save(order);
      OrderDetail orderDetail = new OrderDetail();
      BeanUtils.copyProperties(item,orderDetail);
      log.info("item:{}",item);
      log.info("orderD:{}",orderDetail);
      orderDetail.setOrderId(order.getId());
      orderDetail.setItemId(item.getId());
      orderDetail.setNum(orderxia.getNum());
      orderDetailService.save(orderDetail);

      Address addressById = userClient.findAddressById(orderxia.getAddressId());
      //将地址信息添加
      OrderLogistics orderLogistics = new OrderLogistics();
      BeanUtils.copyProperties(addressById,orderLogistics);
      orderLogisticsService.save(orderLogistics);
      itemClient.updateall(item);


   return order.getId();

   }
}

